/**
 * translateCtrl - Controller for translate
 */
// 多语言控制
function translateCtrl($translate, $scope) {
    $scope.changeLanguage = function (langKey) {
        $translate.use(langKey);
        $scope.language = langKey;
    };
}

// 确认弹窗
function alertModalCtrl($scope, $uibModalInstance, title, content) {
    $scope.alertTitle = title;
    $scope.alertContent = content;
    $scope.confirm = function () {
        $uibModalInstance.close();
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

// 主控
function mainCtrl($scope, $http) {
    $scope.menuRegexp = /_PRIVILEGE/g;
    $http({
        method: 'post',
        url: '/user/getMenuList'
    }).then(function (value) {
        $scope.menuList = value.data;
    });
}

// 主页控制
function homePageCtrl($scope, httpSvc) {
    var barContext = document.getElementById('bar').getContext('2d');
    barContext.canvas.height = 300;
    $scope.barSeries = $scope.barLabels = ['交易总笔数', '成功笔数', '拒付笔数', '退款笔数'];
    $scope.barColors = [
        {backgroundColor: 'rgb(0,151,251)'},
        {backgroundColor: 'rgb(26,179,148)'},
        {backgroundColor: 'rgb(248,172,89)'},
        {backgroundColor: 'rgb(236,71,88)'}];
    $scope.barOptions = {
        scales: {
            xAxes: [{
                barPercentage: 0.5,
                // 是否X轴堆叠
                stacked: true,
                gridLines: {
                    // 是否显示X轴刻度线
                    display: false
                }
            }],
            yAxes: [{
                ticks: {
                    // y轴从0开始
                    beginAtZero: true,
                    // 以1为整
                    stepSize: 1
                },
                gridLines: {
                    // 是否显示Y轴刻度线
                    display: false
                },
                scaleLabel: {
                    // 是否显示Y轴刻说明
                    display: true,
                    // Y轴刻说明
                    labelString: '笔数'
                }
            }]
        },
        tooltips: {
            // 提示类型
            mode: 'point',
            axis: 'y'
        },
        legend: {
            display: true,
            position: 'right',
            labels: {
                boxWidth: 12
            }
        },
        /*layout: {
            padding: {
                left: 50,
                right: 0,
                top: 0,
                bottom: 0
            }
        },*/
        // 是否自动保持长宽比
        maintainAspectRatio: false
    };

    var doughnutContext = document.getElementById('doughnut').getContext('2d');
    doughnutContext.canvas.height = 300;
    $scope.doughnutLabels = ['成功金额', '拒付金额', '退款金额'];
    $scope.doughnutColors = ['rgb(26,179,148)', 'rgb(248,172,89)', 'rgb(236,71,88)'];
    $scope.doughnutOptions = {
        legend: {
            display: true,
            position: 'right',
            labels: {
                boxWidth: 12
            }
        },
        // 是否自动保持长宽比
        maintainAspectRatio: false
    };

    httpSvc.getData('post', '/homePage/tradingToday').then(function (value) {
        $scope.barData = [
            [value.all, 0, 0, 0],
            [0, value.success, 0, 0],
            [0, 0, value.refused, 0],
            [0, 0, 0, value.refund]];
        angular.element('#bar-content').removeClass('sk-loading');
    });

    httpSvc.getData('post', '/homePage/todayTransactionAmount').then(function (value) {
        $scope.doughnutData = [value.success, value.refused, value.refund];
        angular.element('#doughnut-content').removeClass('sk-loading');
    });

    httpSvc.getData('post', '/merchant/getMerchantBalance').then(function (value) {
        $scope.balance = value;
        angular.element('#balance-content').removeClass('sk-loading');
    });

    httpSvc.getData('post', '/homePage/backlog').then(function (value) {
        $scope.financeDrawing = value.financeDrawing;
        $scope.refundUnaudited = value.refundUnaudited;
        $scope.refundFail = value.refundFail;
        angular.element('#backlog-content').removeClass('sk-loading');
    });


    //商户拒付率
    httpSvc.getData('get', '/trans/getRefusedStatistics').then(function (value) {

        var chart = c3.generate({
            data: {
                columns: [ ['data', ((value[0].refusedCount/value[0].count)*100).toFixed(2)] ],
                type: 'gauge'
            },
            gauge: {
                label: {
                    format: function(value, ratio) {
                        return value+"%";
                    },
                    // show: false // to turn off the min/max labels.
                },
                max: 15,
                width: 35
                // units: '拒付率',
            },
            color: {
                pattern: ['#1ab394', '#f8ac59', '#ec4758', '#000000'],
                threshold: { values: ['5','10','15','100'] }
            },
            size: { height: "110" }
        });

    });

}

// 交易查询
function transInfoCtrl($scope, $uibModal, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    var payTypesConcat = [];
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.payModes = value.payModes;
        payTypesConcat = payTypesConcat.concat(value.credit, value.debit, value.yandex, value.qiwi, value.remittance);
        $scope.payTypes = payTypesConcat;
        $scope.bankStatus = value.bankStatus;
        $scope.shipStatus = value.shipStatus;
        $scope.financeStatus = value.financeStatus;
        $scope.init = value;
        getTransStatistics(searchInfo);
        $scope.transTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getTransInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.$watch('searchInfo.payMode', function (newVal) {
        switch (newVal) {
            case 'Credit':
                $scope.payTypes = $scope.init.credit;
                break;
            case 'Debit':
                $scope.payTypes = $scope.init.debit;
                break;
            case 'Yandex':
                $scope.payTypes = $scope.init.yandex;
                break;
            case 'Qiwi':
                $scope.payTypes = $scope.init.qiwi;
                break;
            case 'Remittance':
                $scope.payTypes = $scope.init.remittance;
                break;
            default:
                $scope.payTypes = payTypesConcat;
                break;
        }
    });
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        getTransStatistics(searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.resetForm = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.payTypes = payTypesConcat;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        getTransStatistics(searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.showModal = function (order, type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans/trans_modal',
            controller: 'transModalCtrl',
            size: 'lg',
            resolve: {
                orderInfo: function () {
                    return order;
                },
                financeStatus: function () {
                    return $scope.financeStatus;
                },
                exceptionStatus: function () {
                    return $scope.exceptionStatus;
                },
                type: function () {
                    return type;
                }
            }
        });
        modalInstance.result.then(function () {
        }, function () {
        });
    };
    $scope.exportOrder = function () {
        var title;
        var content;
        var exportInfo = angular.copy(searchInfo);
        var exportMaxSize = 10000;
        // var objectLength = Object.keys(exportInfo).length;
        if ($scope.transTable.total() > exportMaxSize) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>超出系统导出限制数' + exportMaxSize + '条</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出中！'
            });
            $http({
                method: 'post',
                url: '/trans/downloadOrderInfo',
                data: exportInfo,
                responseType: 'blob'
            }).then(function (value) {
                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'tradeList-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };

    function getTransStatistics(value) {
        httpSvc.getData('post', '/trans/getStatistics', value).then(function (value1) {
            $scope.orderStatistics = value1.orderStatistics;
            $scope.orderChangeStatistics = value1.orderChangeStatistics;
        });
    }
}

// 交易查询-交易详情模态框
function transModalCtrl($scope, $uibModalInstance, orderInfo, financeStatus, exceptionStatus, type, httpSvc) {
    $scope.type = type;
    if (type === 1) {
        httpSvc.getData('post', '/trans/getOrderCargoTrack', JSON.stringify(orderInfo.id)).then(function (value) {
            $scope.shipInfo = value;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    } else {
        $scope.orderInfo = angular.copy(orderInfo);
        $scope.financeStatus = financeStatus;
        $scope.exceptionStatus = exceptionStatus;
        httpSvc.getData('post', '/trans/getDetail', orderInfo).then(function (value) {
            $scope.merchantOrder = value.merchantOrder;
            $scope.merchantOrderRmb = value.merchantOrderRmb;
            $scope.orderDetail = value.orderDetail;
            $scope.simpleCard = value.simpleCard;
            $scope.orderChange = value.orderChange;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    }
}

// 保证金查询
function transBondInfoCtrl($scope, $timeout, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {timeSearchType: 0, idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    var init;
    var totalItems;
    $scope.orderTypeTxt = '平台订单号';
    $scope.timeTypeTxt = '交易日期';
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    $scope.timeSwitch = function ($event, timeSearchType) {
        $scope.searchInfo.timeSearchType = timeSearchType;
        $scope.timeTypeTxt = angular.element($event.target).text();
    };
    var oldEndDate;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    httpSvc.getData('post', '/trans/getBondInit').then(function (value) {
        init = value;
        $scope.siteUrls = value.siteUrls;
        $scope.bondStatus = value.bondStatus;
        getTransBondStatistics(searchInfo);
        $scope.bondTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getBondInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    totalItems = value.total;
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $timeout(function () {
        $scope.$watch('searchInfo.merId', function (newVal) {
            if (init !== undefined) {
                if (newVal !== undefined) {
                    var urls = [];
                    for (var i = 0; i < init.siteUrls.length; i++) {
                        if (init.siteUrls[i].merId === newVal) {
                            urls.push(init.siteUrls[i]);
                        }
                    }
                    $scope.siteUrls = urls;
                } else {
                    $scope.siteUrls = init.siteUrls;
                }
            }
        });
        $scope.$watch('searchInfo.startDate', function (newVal) {
            if (newVal !== undefined && newVal !== null) {
                $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
                $scope.endDateDisable = false;
                if (oldEndDate !== undefined) {
                    $scope.searchInfo.endDate = oldEndDate;
                }
            } else {
                $scope.endDateDisable = true;
                oldEndDate = $scope.searchInfo.endDate;
                $scope.searchInfo.endDate = undefined;
            }
        });
        $scope.$watch('searchInfo.endDate', function (newVal) {
            if (newVal !== undefined && newVal !== null) {
                $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
            } else {
                $scope.dateOptions1.maxDate = new Date();
            }
        });
    });
    $scope.search = function () {
        searchInfo = angular.copy($scope.searchInfo);
        getTransBondStatistics(searchInfo);
        $scope.bondTable.page(1);
        $scope.bondTable.reload();
    };
    $scope.resetSearchInfo = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        getTransBondStatistics(searchInfo);
        $scope.bondTable.page(1);
        $scope.bondTable.reload();
    };
    $scope.exportBond = function () {
        console.log(searchInfo);
        if ($scope.bondTable.total() <= 50000 || angular.equals(searchInfo, defaultSearch)) {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出数据中！'
            });
            $http({
                method: 'post',
                url: '/trans/downloadBondInfo',
                data: searchInfo,
                responseType: 'blob'
            }).then(function (value) {
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'bondList-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
        } else {
            toaster.pop({
                type: 'warning',
                title: '导出数据',
                body: '导出数据超过50 000条！'
            });
        }
    };

    function getTransBondStatistics(value) {
        httpSvc.getData('post', '/trans/getBondStatistics', value).then(function (value1) {
            $scope.orderStatistics = value1.orderStatistics;
            $scope.bondStatistics = value1.bondStatistics;
        });
    }
}

// 交易变更
function transChangeCtrl($scope, $uibModal, toaster, NgTableParams, httpSvc) {
    var defaultSearch = {idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    var payTypesConcat = [];
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.bankStatus = value.bankStatus;
        $scope.init = value;
        $scope.transTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getTransInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.resetForm = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.payTypes = payTypesConcat;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.showModal = function (order) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans/trans_change_modal',
            controller: 'transChangeModalCtrl',
            // size: 'sm',
            resolve: {
                orderInfo: function () {
                    return order;
                }
            }
        });
        modalInstance.result.then(function () {
        }, function () {
        });
    };
}

// 交易变更模态框
function transChangeModalCtrl($scope, $uibModalInstance, orderInfo, httpSvc) {
    $scope.orderChange = {'type': 2};
    $scope.orderInfo = orderInfo;
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    httpSvc.getData('post', '/trans/getMerchantOrder', orderInfo.id).then(function (value) {
        $scope.merchantOrder = value;
        $scope.orderChange['orderId'] = orderInfo.id;
        $scope.maxAmount = $scope.merchantOrder.sourceAmount -
            ($scope.merchantOrder.sourceRefund === undefined ? 0 : $scope.merchantOrder.sourceRefund) -
            ($scope.merchantOrder.sourceProtest === undefined ? 0 : $scope.merchantOrder.sourceProtest);
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.amountChange = function () {
        if ($scope.orderChange.amount != null) {
            if ($scope.orderChange.amount < 0) {
                $scope.orderChange.amount = null;
            } else if ($scope.orderChange.amount > $scope.maxAmount) {
                $scope.orderChange.amount = $scope.maxAmount;
            }
        }
    };
    $scope.confirm = function () {
        httpSvc.getData('post', '/trans/orderChange', $scope.orderChange).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '订单变更',
                    body: '订单变更成功！'
                });
                $uibModalInstance.close(value);
            } else {
                toaster.pop({
                    type: 'error',
                    title: '订单变更',
                    body: '订单变更失败！'
                });
            }
        });
    };
    $scope.confirmDisabled = function (myForm) {
        return !myForm.$valid;
    };
}

// 退款查询
function transRefundCtrl($scope, $uibModal, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    $scope.changeType = [
        {name: '全额退款', firstValue: 2},
        {name: '部分退款', firstValue: 3}];
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.auditedStatus = value.auditedStatus;
        $scope.refundTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getRefundInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.refundTable.page(1);
        $scope.refundTable.reload();
    };
    $scope.resetForm = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        $scope.refundTable.page(1);
        $scope.refundTable.reload();
    };
    $scope.exportOrderChange = function () {
        var title;
        var content;
        var exportInfo = angular.copy(searchInfo);
        var exportMaxSize = 10000;
        if ($scope.refundTable.total() > exportMaxSize) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>超出系统导出限制数' + exportMaxSize + '条</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出中！'
            });
            $http({
                method: 'post',
                url: '/trans/downloadRefundInfo',
                data: exportInfo,
                responseType: 'blob'
            }).then(function (value) {
                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'refundList-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };
}

// 拒付查询
function transRefusedCtrl($scope, $uibModal, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.auditedStatus = value.auditedStatus;
        $scope.refusedTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getRefusedInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.refusedTable.page(1);
        $scope.refusedTable.reload();
    };
    $scope.resetForm = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        $scope.refusedTable.page(1);
        $scope.refusedTable.reload();
    };
    $scope.exportOrderChange = function () {
        var title;
        var content;
        var exportInfo = angular.copy(searchInfo);
        var exportMaxSize = 10000;
        // var objectLength = Object.keys(exportInfo).length;
        if ($scope.refusedTable.total() > exportMaxSize) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>超出系统导出限制数' + exportMaxSize + '条</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出中！'
            });
            $http({
                method: 'post',
                url: '/trans/downloadRefusedInfo',
                data: exportInfo,
                responseType: 'blob'
            }).then(function (value) {
                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'refusedList-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };
}

// 余额查询
function balanceInquiryCtrl($scope, $uibModal, NgTableParams, httpSvc) {
    httpSvc.getData('post', '/merchant/getMerchantBalance').then(function (value) {
        $scope.balance = value;
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.showModal = function (type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/account/balance_inquiry_modal',
            controller: 'balanceInquiryModalCtrl',
            size: type === 0 ? 'lg' : null,
            resolve: {
                balance: function () {
                    return $scope.balance;
                },
                type: function () {
                    return type;
                }
            }
        });
        modalInstance.result.then(function () {
        }, function () {
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    }
}

// 余额查询模态框
function balanceInquiryModalCtrl($scope, $uibModalInstance, toaster, balance, type, httpSvc) {
    $scope.type = type;
    if (type === 0) {

    } else {
        $scope.balance = balance;
        // $scope.balance = 123;
        $scope.amountChange = function () {
            if ($scope.balance > 0 && $scope.amount != null) {
                if ($scope.amount > $scope.balance) {
                    $scope.amount = $scope.balance;
                }
            }
        };
        $scope.confirmDisabled = function () {
            return !$scope.myForm.$valid || !($scope.amount > 0);
        };
        $scope.confirm = function () {
            httpSvc.getData('post', '/merchant/financeDrawingApplication', JSON.stringify($scope.amount)).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '余额提现',
                        body: '提现成功！'
                    });
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '余额提现',
                        body: '提现失败！'
                    });
                }
            });
        };
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }
}

// 提现查询
function withdrawDepositInquiryCtrl($scope, NgTableParams, httpSvc) {
    $scope.searchInfo = {};
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    httpSvc.getData('post', '/merchant/getFinanceDrawingInit').then(function (value) {
        $scope.financeDrawingStatus = value.financeDrawingStatus;
        $scope.financeDrawingTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/merchant/getFinanceDrawing', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: $scope.searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.search = function () {
        $scope.financeDrawingTable.page(1);
        $scope.financeDrawingTable.reload();
    };
    $scope.resetForm = function () {
        $scope.searchInfo = {};
        $scope.financeDrawingTable.page(1);
        $scope.financeDrawingTable.reload();
    };
}

// 域名管理
function webSiteMgmtCtrl($scope, $uibModal, NgTableParams, toaster, httpSvc, $filter) {

    $scope.searchInfo = {};

    /*httpSvc.getData('post', '/risk/getWebSiteMgmtInit').then(function (value) {
        $scope.siteUrls = value.siteUrls;
        $scope.statusConstant = value.statusConstant;
    });

    $scope.webSiteTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/risk/getWebSiteMgmtInfo', {
                pageNum: params.page(),
                pageSize: params.count(),
                orderBy: params.sorting(),
                searchInfo: $scope.searchInfo
            }).then(function (value) {
                params.total(value.total);
                angular.element('.ibox-content').removeClass('sk-loading');
                return value.rows;
            });
        }
    });

    $scope.search = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.webSiteTable.page(1);
        $scope.webSiteTable.reload();
    };

    $scope.resetForm = function () {
        $scope.searchInfo = {};
        $scope.webSiteTable.page(1);
        $scope.webSiteTable.reload();
    };

    $scope.showModal = $scope.edit = function (type, currentData) {

        modalInstance = $uibModal.open({
            templateUrl: '/views/risk/web_site_mgmt_modal',
            controller: 'webSiteMgmtModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                currentData: function () {
                    return currentData;
                },
                webSiteTable: function () {
                    return $scope.webSiteTable;
                }
            }
        });
        modalInstance.result.then(function () {

        }, function () {

        });
    };

    $scope.delModal = function (row) {

        var modalInstance = $uibModal.open({
            templateUrl: '/views/common/alert_modal',
            controller: 'alertModalCtrl',
            resolve: {
                row: function () {
                    return row;
                },
                title: function () {
                    return "删除确认";
                },
                content: function () {
                    return "<div class=\"text-center\">" +
                        "<di>确定要删除这条数据吗 ?</di>";
                }
            }
        });
        modalInstance.result.then(function () {
            httpSvc.getData('post', '/risk/deleteWebSite', row).then(function (value) {
                if (value == 1) {
                    toaster.pop({
                        type: 'success',
                        title: '成功',
                        body: '删除成功！'
                    });
                    $scope.webSiteTable.page();
                    $scope.webSiteTable.reload();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '删除失败',
                        body: "该网站已有交易，不能执行删除!"
                    });
                }
            });

        }, function () {

        });
    }*/

    $scope.showModal = $scope.edit = function (type, currentData) {
        modalInstance = $uibModal.open({
            templateUrl: '/views/risk/web_site_mgmt_modal',
            controller: 'webSiteMgmtModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                currentData: function () {
                    return currentData;
                },
                webSiteTable: function () {
                    return $scope.webSiteTable;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {

        });
    };
    $scope.delModal = function (row) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/common/alert_modal',
            controller: 'alertModalCtrl',
            resolve: {
                row: function () {
                    return row;
                },
                title: function () {
                    return "删除确认";
                },
                content: function () {
                    return "<div class=\"text-center\">" +
                        "<di>确定要删除这条数据吗 ?</di>";
                }
            }
        });
        modalInstance.result.then(function () {
            httpSvc.getData('post', '/merchant/webSite/delete', [row.id]).then(function (value) {
                if (value.length === 0) {
                    toaster.pop({
                        type: 'success',
                        title: '成功',
                        body: '删除成功！'
                    });
                    tableReload();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '删除失败',
                        body: "该网站已有交易，不能执行删除!"
                    });
                }
            });
        }, function () {

        });
    };
    httpSvc.getData('post', '/merchant/getMerchantWebSiteInit').then(function (value) {
        $scope.webSiteStatus = value.webSiteStatus;
        $scope.industryType = value.industryType;
        httpSvc.getData('post', '/merchant/getAllMerchantWebSite').then(function (value) {
            $scope.merchantWebSite = value;
            $scope.webSiteTable = new NgTableParams({}, {
                filterOptions: {filterFn: dateRangeFilter},
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.search = function () {
        angular.extend($scope.webSiteTable.filter(), $scope.searchInfo);
    };
    $scope.resetForm = function () {
        $scope.searchInfo = {};
        $scope.webSiteTable.filter({});
    };
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {

        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

    // 自定义ng-Table Filter
    function dateRangeFilter(data, filterValues/*, comparator*/) {
        if (filterValues.startDate == null && filterValues.endDate == null) {
            return $filter('filter')(data, filterValues);
        } else {
            var start = null;
            var end = null;
            if (filterValues.startDate == null && filterValues.endDate != null) {
                end = filterValues.endDate;
                delete filterValues.endDate;
            } else if (filterValues.startDate != null && filterValues.endDate == null) {
                start = filterValues.startDate;
                delete filterValues.startDate;
            } else {
                start = filterValues.startDate;
                end = filterValues.endDate;
                delete filterValues.startDate;
                delete filterValues.endDate;
            }
            return $filter('filter')(data, filterValues).filter(function (item) {
                if (start != null && end == null) {
                    return start <= item.createTime;
                } else if (start != null && end != null) {
                    return start <= item.createTime && end >= item.createTime;
                } else {
                    return true;
                }
            });
        }
    }
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/merchant/getAllMerchantWebSite').then(function (value) {
            $scope.webSiteTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 域名管理模态框
function webSiteMgmtModalCtrl($scope, $uibModalInstance, httpSvc, toaster, type, currentData) {
    $scope.isExist = type === 0;
    $scope.type = type;
    $scope.tempData = angular.copy(currentData);
    //正则 域名校验
    $scope.strRegex = "^((https|http|ftp|rtsp|mms)?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
        + "|" // 允许IP和DOMAIN（域名）
        + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        + "[a-z]{2,6})" + "(:[0-9]{1,4})?" // 端口- :80
        + "((/?)|" + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";

    $scope.urlBlur = function ($event, value) {
        if (!verification(value, $event.target) && type === 0) {
            httpSvc.getData('post', '/merchant/webSite/isExist', JSON.stringify(value)).then(function (value) {
                if (value) {
                    $scope.isExist = verification(null, $event.target);
                } else {
                    $scope.isExist = false;
                }
            });
        }
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };

    $scope.confirm = function () {
        var recods;
        if (0 === type) { //新增
            recods = {url: '/merchant/webSite/add', title: "新增", successMsg:"添加成功！", errorMsg: "添加失败！"};
        } else { //编辑
            recods = {url: '/merchant/webSite/update', title: "编辑", successMsg:"编辑成功！", errorMsg: "编辑失败！"};
        }
        httpSvc.getData('post', recods.url, $scope.tempData).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: recods.title,
                    body: recods.successMsg
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: recods.title,
                    body: recods.errorMsg
                });
            }
            $uibModalInstance.close();
        })
    }
}

// 物流管理
function logisticsMgmtCtrl($scope, $uibModal, $filter, NgTableParams, toaster, httpSvc, $http) {

    $scope.searchInfo = {};

    $scope.orderTypeTxt = '平台订单号';
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };

    httpSvc.getData('post', '/risk/getLogisticsMgmtInit').then(function (value) {
        $scope.shipStatus = value.shipStatus;
        $scope.expressText = value.express;
        $scope.siteUrls = value.siteUrl;

    });

    $scope.logisticsMgmtTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/risk/getLogisticsMgmtInfo', {
                pageNum: params.page(),
                pageSize: params.count(),
                orderBy: params.sorting(),
                searchInfo: $scope.searchInfo
            }).then(function (value) {
                params.total(value.total);
                angular.element('.ibox-content').removeClass('sk-loading');
                return value.rows;
            });
        }
    });

    $scope.search = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.logisticsMgmtTable.page(1);
        $scope.logisticsMgmtTable.reload();
    };

    $scope.resetForm = function () {
        $scope.searchInfo = {};
        $scope.orderTypeTxt = '平台订单号';
        $scope.logisticsMgmtTable.page(1);
        $scope.logisticsMgmtTable.reload();
    };

    $scope.showModal = $scope.edit = function (orderId) {

        modalInstance = $uibModal.open({
            templateUrl: '/views/risk/logistics_mgmt_modal',
            controller: 'logisticsMgmtModalCtrl',
            resolve: {
                orderId: function () {
                    return orderId;
                },
                expressName: function () {
                    return $scope.expressText;
                },
                logisticsMgmtTable: function () {
                    return $scope.logisticsMgmtTable;
                }
            }
        });
        modalInstance.result.then(function () {

        }, function () {

        });
    };

    $scope.exportOrder = function () {
        var title;
        var content;
        var exportInfo = angular.copy($scope.searchInfo);
        var exportMaxSize = 10000;
        // var objectLength = Object.keys(exportInfo).length;
        if ($scope.logisticsMgmtTable.total() > exportMaxSize) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>超出系统导出限制数' + exportMaxSize + '条</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出中！'
            });
            $http({
                method: 'post',
                url: '/risk/downloadOrderInfo',
                data: exportInfo,
                responseType: 'blob'
            }).then(function (value) {

                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'logisticsMgmt-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
            // }, function () {
            // });
        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };

    $scope.batchUpload = function () {

        modalInstance = $uibModal.open({
            templateUrl: '/views/risk/logistics_mgmt_upload_modal',
            controller: 'logisticsMgmtUploadModalCtrl',
            size: 'lg',
            resolve: {
                logisticsMgmtTable: function () {
                    return $scope.logisticsMgmtTable;
                }
            }
        });
        modalInstance.result.then(function () {
        }, function () {

        });
    };

    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {

        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

}

// 物流管理模态框
function logisticsMgmtModalCtrl($scope, $uibModalInstance, httpSvc, toaster, orderId, expressName, logisticsMgmtTable) {

    $scope.expressModel = {};
    $scope.expressModel.orderId = orderId;
    $scope.expressName = expressName;
    $scope.logisticsMgmtTable = logisticsMgmtTable;

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };

    $scope.confirm = function () {
        httpSvc.getData('post', '/risk/uploadExpressInfo', $scope.expressModel).then(function (value) {
            if (value == 1) {

                toaster.pop({
                    type: 'success',
                    title: '上传',
                    body: '上传成功！'
                });
                $scope.logisticsMgmtTable.page();
                $scope.logisticsMgmtTable.reload();

            } else {
                var msg = "上传失败！";
                value.msg != "" ? msg = msg + value.msg : "";
                toaster.pop({
                    type: 'error',
                    title: '上传',
                    body: msg
                });
            }
            $uibModalInstance.dismiss();

        });
    }

}

// 批量上传弹窗
function logisticsMgmtUploadModalCtrl($scope, $uibModalInstance, httpSvc, toaster, csvExp, NgTableParams, FileUploader, logisticsMgmtTable) {

    $scope.result = {};
    $scope.logisticsMgmtTable = logisticsMgmtTable;
    $scope.uploader = new FileUploader({
        url: '/risk/batchOperation'
    });

    $scope.uploader.onCompleteItem = function (item, response, status) {

        if (status === 200 && response != 0) {
            toaster.pop({
                type: 'success',
                title: '批量操作',
                body: '文件：' + item.file.name + ' 上传成功！'
            });

        } else {
            toaster.pop({
                type: 'error',
                title: '批量操作',
                body: '文件：' + item.file.name + ' 上传失败！'
            });
        }
        $scope.result.status = status;
        $scope.result.response = response;

    };

    $scope.cancel = function () {

        $uibModalInstance.dismiss('cancel');
        if ($scope.result.status === 200 && $scope.result.response != 0) {
            $scope.logisticsMgmtTable.page(1);
            $scope.logisticsMgmtTable.reload();
        }
    };

    // $scope.example = function (type) {
    //     var csvData = {
    //         'data': [{'orderId': 1800000000000, 'amount': 100.00, 'reasons': '退款理由', 'remark': '非必填'}],
    //         'fileName': '批量退款',
    //         'columns': {
    //             'title': ['平台订单号', '商户订单号', '域名', '交易时间','状态','快递公司','快递单号','查单网址','上传时间'],
    //             'key': ['orderId', 'amount', 'reasons', 'remark']
    //         }
    //     };
    //     if (type === 4) {
    //         csvData = {
    //             'data': [{'orderId': 1800000000000, 'reasons': '拒付理由', 'remark': '非必填'}],
    //             'fileName': '批量拒付',
    //             'columns': {
    //                 'title': ['平台订单号', '理由', '备注'],
    //                 'key': ['orderId', 'reasons', 'remark']
    //             }
    //         };
    //     }
    //     if (csvExp.export(csvData)) {
    //         toaster.pop({
    //             type: 'success',
    //             title: '批量操作',
    //             body: '示例导出成功！'
    //         });
    //     } else {
    //         toaster.pop({
    //             type: 'warning',
    //             title: '批量操作',
    //             body: '示例导出失败！'
    //         });
    //     }
    // }


}

// 商户基本信息
function baseInformationCtrl($scope, httpSvc, toaster, FileUploader) {
    var merchantInfo;
    var certificateImgUrl = [];
    httpSvc.getData('post', '/merchant/getBaseInformationInit').then(function (value) {
        merchantInfo = angular.copy(value.merchantInfo);
        if (value.merchantInfo.certificate.trim() !== '') {
            $scope.certificateImgUrl = value.merchantInfo.certificate.split(',');
            certificateImgUrl = angular.copy($scope.certificateImgUrl);
        } else {
            $scope.certificateImgUrl = [];
        }
        $scope.merchantInfo = value.merchantInfo;
        $scope.provinceInfo = value.provinceInfo;
        $scope.merchantCategory = value.merchantCategory;
        $scope.$watch('merchantInfo.province', function (newVal) {
            if (newVal !== undefined) {
                for (var i = 0; i < $scope.provinceInfo.length; i++) {
                    if ($scope.provinceInfo[i].id === newVal) {
                        $scope.cityInfo = $scope.provinceInfo[i].childArea;
                        break;
                    }
                }
            }
        });
        $scope.$watch('merchantInfo.city', function (newVal) {
            if (newVal !== undefined && $scope.cityInfo !== undefined) {
                for (var i = 0; i < $scope.cityInfo.length; i++) {
                    if ($scope.cityInfo[i].id === newVal) {
                        $scope.areaInfo = $scope.cityInfo[i].childArea;
                        break;
                    }
                }
            }
        });
        $scope.provinceChange = function () {
            $scope.merchantInfo.city = null;
            $scope.merchantInfo.area = null;
        };
        $scope.cityChange = function () {
            $scope.merchantInfo.area = null;
        };
    });
    $scope.uploader = new FileUploader({
        url: '/merchant/uploadMerchantCertificate'
    });
    /*$scope.uploader.onAfterAddingFile = function () {
        $scope.uploader.uploadAll();
    };*/
    $scope.uploader.onAfterAddingAll = function () {
        $scope.uploader.uploadAll();
    };
    $scope.uploader.onSuccessItem = function (item, response, status, headers) {
        $scope.certificateImgUrl.push(response);
    };
    $scope.uploader.onCompleteAll = function () {
        $scope.uploader.clearQueue();
    };
    $scope.confirmDisabled = function (myForm) {
        return !myForm.$valid || (angular.equals(merchantInfo, $scope.merchantInfo) && angular.equals(certificateImgUrl, $scope.certificateImgUrl));
    };
    $scope.confirm = function () {
        $scope.merchantInfo.certificate = $scope.certificateImgUrl.toString();
        httpSvc.getData('post', '/merchant/updateMerchantInfo', $scope.merchantInfo).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '更新商户信息',
                    body: '更新商户信息成功！'
                });
                merchantInfo = angular.copy($scope.merchantInfo);
            } else {
                toaster.pop({
                    type: 'warning',
                    title: '更新商户信息',
                    body: '更新商户信息失败！'
                });
            }
        });
    };
}

// 配置信息
function configurationInformation($scope, httpSvc) {
    httpSvc.getData('post', '/merchant/getConfigurationInformation').then(function (value) {
        $scope.merchantSetting = value.merchantSetting;
        $scope.trackSetting = value.trackSetting;
        $scope.trackAudit = value.trackAudit;
        $scope.correctDistribute = value.correctDistribute;
        $scope.currency = value.currency;
    });
}

// 支付信息
function paymentInformation($scope, httpSvc) {
    $scope.payModeTable = {};
    $scope.payRowspan = 0;
    httpSvc.getData('post', '/merchant/getPaymentInformation').then(function (value) {
        $scope.encrypt = value.encrypt;
        $scope.status = value.status;
        $scope.merchantPay = value.merchantPay;
        $scope.payMode = value.payMode;
        $scope.bailCycle = value.merchantRate[0].bailCycle;
        $scope.bailRate = value.merchantRate[0].bailRate;
        var payMode = value.merchantPay.payMode.replace(/[^a-zA-z,]/g, '').split(',');
        // $scope.payModeTable
        for (var i = 0; i < payMode.length; i++) {
            $scope.payModeTable[payMode[i]] = [];
            for (var j = 0; j < value.merchantRate.length; j++) {
                if (value.merchantRate[j].payMode === payMode[i])
                    $scope.payModeTable[payMode[i]].push(value.merchantRate[j]);
            }
            $scope.payRowspan += $scope.payModeTable[payMode[i]].length;
        }
    });
}

// 用户管理
function userMgmtCtrl($scope, $uibModal, toaster, NgTableParams, httpSvc) {
    httpSvc.getData('post', '/user/getRoleList').then(function (value) {
        $scope.roleList = value;
    });
    httpSvc.getData('post', '/user/getUserList').then(function (value) {
        $scope.userTable = new NgTableParams({}, {
            dataset: value
        });
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.showModal = function (type, userInfo) {
        var modalInstance;
        if (type !== 3) {
            modalInstance = $uibModal.open({
                templateUrl: '/views/system/user_modal',
                controller: 'userMgmtModalCtrl',
                resolve: {
                    userInfo: function () {
                        return userInfo;
                    },
                    roleList: function () {
                        return $scope.roleList;
                    },
                    type: function () {
                        return type;
                    }
                }
            });
            modalInstance.result.then(function () {
                tableReload();
            }, function () {
            });
        } else {
            var title = '删除确认';
            var content =
                '<div class="text-center">' +
                '<strong>确定要删除这1条数据吗？</strong>' +
                '</div>';
            modalInstance = $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
            modalInstance.result.then(function () {
                httpSvc.getData('post', '/user/delete', JSON.stringify(userInfo.userName)).then(function (value) {
                    tableReload();
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '用户管理',
                            body: '删除用户成功！'
                        });
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '用户管理',
                            body: '删除用户失败！'
                        });
                    }
                });
            }, function () {
            });
        }
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/user/getUserList').then(function (value) {
            $scope.userTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 用户管理模态框
function userMgmtModalCtrl($scope, $uibModalInstance, toaster, httpSvc, userInfo, roleList, type) {
    $scope.userInfo = angular.copy(userInfo);
    $scope.roleList = roleList;
    $scope.type = type;
    var isExist = true;
    var passwordValid = false;
    var passwordValidB = false;
    $scope.userNameBlur = function ($event, userName) {
        if (!verification(userName, $event.target)) {
            httpSvc.getData('post', '/user/isExist', {userName: userName}).then(function (value) {
                if (value) {
                    verification(null, $event.target);
                    isExist = true;
                } else {
                    verification(userName, $event.target);
                    isExist = false;
                }
            });
        }
    };
    $scope.passwordBlur = function ($event, password) {
        if (password != null && password.length < 6) {
            verification(null, $event.target);
            passwordValid = false;
        } else {
            verification(password, $event.target);
            passwordValid = true;
        }
    };
    $scope.passwordChange = function () {
        passwordValidB = false;
        if ($scope.userInfo.passwordB != null && $scope.userInfo.password !== $scope.userInfo.passwordB) {
            angular.element('#passwordB').parent().removeClass('has-success');
            angular.element('#passwordB').parent().addClass('has-error');
        }
    };
    $scope.passwordBBlur = function ($event, passwordB) {
        if ($scope.userInfo != null && $scope.userInfo.password !== passwordB) {
            verification(null, $event.target);
            passwordValidB = false;
        } else {
            verification(passwordB, $event.target);
            passwordValidB = true;
        }
    };
    $scope.realNameBlur = $scope.mobileBlur = $scope.emailBlur = function ($event, value) {
        verification(value, $event.target);
    };
    switch (type) {
        case 0:
            $scope.confirmDisabled = function (myForm) {
                return !myForm.$valid || isExist || !passwordValid || !passwordValidB;
            };
            $scope.confirm = function () {
                httpSvc.getData('post', '/user/add', $scope.userInfo).then(function (value) {
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '用户管理',
                            body: '新增用户成功！'
                        });
                        $uibModalInstance.close();
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '用户管理',
                            body: '新增用户失败！'
                        });
                    }
                });
            };
            break;
        case 1:
            $scope.confirmDisabled = function (myForm) {
                return !myForm.realName.$valid || !myForm.mobile.$valid || !myForm.email.$valid ||
                    !myForm.roleId.$valid || angular.equals($scope.userInfo, userInfo);
            };
            $scope.confirm = function () {
                httpSvc.getData('post', '/user/update', $scope.userInfo).then(function (value) {
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '用户管理',
                            body: '编辑用户成功！'
                        });
                        $uibModalInstance.close();
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '用户管理',
                            body: '编辑用户失败！'
                        });
                    }
                });
            };
            break;
        case 2:
            $scope.confirmDisabled = function () {
                return !passwordValid || !passwordValidB;
            };
            $scope.confirm = function () {
                httpSvc.getData('post', '/user/update', $scope.userInfo).then(function (value) {
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '用户管理',
                            body: '重置密码成功！'
                        });
                        $uibModalInstance.close();
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '用户管理',
                            body: '重置密码失败！'
                        });
                    }
                });
            };
            break;
        default:
            break;
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

// 角色管理
function roleMgmtCtrl($scope, $uibModal, toaster, NgTableParams, httpSvc) {
    httpSvc.getData('post', '/role/getPrivilegeList').then(function (value) {
        $scope.privilegeList = value;
    });
    httpSvc.getData('post', '/role/getRoleList').then(function (value) {
        for (var i = 0; i < value.length; i++) {
            if (value[i].privilegesId != null && value[i].privilegesId !== '') {
                value[i]['privilegeIdList'] = value[i].privilegesId.replace(/[^\d,]/g, '').split(',');
            }
        }
        $scope.roleTable = new NgTableParams({}, {
            dataset: value
        });
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.showModal = function (type, roleInfo) {
        var modalInstance;
        if (type !== 2) {
            modalInstance = $uibModal.open({
                templateUrl: '/views/system/role_modal',
                controller: 'roleMgmtModalCtrl',
                resolve: {
                    roleInfo: function () {
                        return roleInfo;
                    },
                    privilegeList: function () {
                        return $scope.privilegeList;
                    },
                    type: function () {
                        return type;
                    }
                }
            });
            modalInstance.result.then(function () {
                tableReload();
            }, function () {
            });
        } else {
            var title = '删除确认';
            var content =
                '<div class="text-center">' +
                '<strong>确定要删除这1条数据吗？</strong>' +
                '</div>';
            modalInstance = $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
            modalInstance.result.then(function () {
                httpSvc.getData('post', '/role/delete', JSON.stringify(roleInfo.roleName)).then(function (value) {
                    tableReload();
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '角色管理',
                            body: '删除角色成功！'
                        });
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '角色管理',
                            body: '删除角色失败！'
                        });
                    }
                });
            }, function () {
            });
        }
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/user/getRoleList').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                if (value[i].privilegesId != null && value[i].privilegesId !== '') {
                    value[i]['privilegeIdList'] = value[i].privilegesId.replace(/[^\d,]/g, '').split(',');
                }
            }
            $scope.roleTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 角色管理模态框
function roleMgmtModalCtrl($scope, $uibModalInstance, toaster, httpSvc, roleInfo, type, privilegeList) {
    $scope.privilegeList = [];
    for (var i = 0; i < privilegeList.length; i++) {
        if (privilegeList[i].parentId === undefined) {
            var privilege = privilegeList[i];
            privilege['submenu'] = [];
            for (var j = 0; j < privilegeList.length; j++) {
                if (privilegeList[j].parentId === privilegeList[i].id) {
                    privilege.submenu.push(privilegeList[j]);
                }
            }
            $scope.privilegeList.push(privilege);
        }
    }
    $scope.exists = function (value, selected) {
        if (value === undefined || selected === undefined) {
            return false;
        }
        return selected.indexOf(value) > -1;
    };
    $scope.toggle = function (value, selected) {
        var index = selected.indexOf(value);
        if (index > -1) {
            selected.splice(index, 1);
        } else {
            selected.push(value);
        }
    };
    $scope.type = type;
    if (type === 0) {
        $scope.exist = true;
        $scope.nameValid = false;
        $scope.roleInfo = {privilegeIdList: []};
        $scope.nameBlur = function ($event, roleName) {
            httpSvc.getData('post', '/role/isExist', {roleName: roleName}).then(function (value) {
                if (value) {
                    verification(null, $event.target);
                    $scope.exist = true;
                } else {
                    verification(roleName, $event.target);
                    $scope.exist = false;
                }
            });
        };
    } else {
        $scope.exist = false;
        $scope.roleInfo = angular.copy(roleInfo);
        if ($scope.roleInfo.privilegeIdList == null) {
            $scope.roleInfo.privilegeIdList = [];
        }
    }
    $scope.confirm = function () {
        $scope.roleInfo.privilegesId = $scope.roleInfo.privilegeIdList.toString();
        if (type === 0) {
            httpSvc.getData('post', '/role/add', $scope.roleInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '角色管理',
                        body: '新增角色成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '角色管理',
                        body: '新增角色失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/role/update', $scope.roleInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '角色管理',
                        body: '修改角色成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '角色管理',
                        body: '修改角色失败！'
                    });
                }
            });
        }
    };
    $scope.confirmDisabled = function (myForm) {
        return type === 0 ? !myForm.$valid || $scope.exist : false;
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

// 密钥修改
function secretKeyChangeCtrl($scope, httpSvc, toaster) {
    httpSvc.getData('post', '/merchant/getMerchantPay').then(function (value) {
        $scope.merchantPay = value;
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.confirm = function (newKey, userPassword) {
        var merchantPay = angular.copy($scope.merchantPay);
        merchantPay.secretKey = newKey;
        merchantPay.modifier = userPassword;
        httpSvc.getData('post', '/merchant/updateMerchantPay', merchantPay).then(function (value) {
            if (value) {
                $scope.newSecretKey = null;
                $scope.userPassword = null;
                toaster.pop({
                    type: 'success',
                    title: '密钥修改',
                    body: '修改成功！'
                });
                $scope.merchantPay.secretKey = newKey;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '密钥修改',
                    body: '修改失败！'
                });
            }
        });
    };
}

// 意见与建议
function opinionCtrl($scope, $uibModal, toaster, NgTableParams, httpSvc) {
    var searchInfo = {};
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy-MM-dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    httpSvc.getData('post', '/system/getOpinionInit').then(function (value) {
        $scope.questionType = value.questionType;
        $scope.questionStatus = value.questionStatus;
        $scope.opinionTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/system/getOpinion', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.search = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.opinionTable.page(1);
        $scope.opinionTable.reload();
    };
    $scope.resetForm = function () {
        searchInfo = {};
        $scope.searchInfo = {};
        $scope.opinionTable.page(1);
        $scope.opinionTable.reload();
    };
    $scope.showModal = function (type, opinionInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/system/opinion_modal',
            controller: 'opinionModalCtrl',
            resolve: {
                opinionInfo: function () {
                    return opinionInfo;
                },
                questionType: function () {
                    return $scope.questionType;
                },
                type: function () {
                    return type;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {
        });
    };

    function tableReload() {
        $scope.opinionTable.page(1);
        $scope.opinionTable.reload();
    }
}

// 意见与建议模态框
function opinionModalCtrl($scope, $uibModalInstance, toaster, httpSvc, opinionInfo, questionType, type, taOptions) {
    $scope.opinionInfo = angular.copy(opinionInfo);
    $scope.questionType = questionType;
    $scope.type = type;
    taOptions.toolbar = [
        ['h1', 'h2', 'p', 'quote', 'bold', 'italics', 'underline'],
        ['undo', 'redo', 'clear'],
        ['ul', 'ol', 'justifyLeft', 'justifyCenter', 'justifyRight', 'indent', 'outdent', 'insertLink']
    ];
    $scope.textBlur = function (content) {
        $scope.opinionInfo.content = content;
    };
    $scope.confirmDisabled = function (myForm) {
        return !myForm.$valid;
    };
    $scope.confirm = function () {
        if (type === 0) {
            httpSvc.getData('post', '/system/addOpinion', $scope.opinionInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '建议与意见',
                        body: '新增成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '建议与意见',
                        body: '新增失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/system/updateOpinion', $scope.opinionInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '建议与意见',
                        body: '编辑成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '建议与意见',
                        body: '编辑失败！'
                    });
                }
            });
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

angular
    .module('inspinia')
    .controller('mainCtrl', mainCtrl)
    .controller('translateCtrl', translateCtrl)
    .controller('alertModalCtrl', alertModalCtrl)
    .controller('homePageCtrl', homePageCtrl)
    .controller('transInfoCtrl', transInfoCtrl)
    .controller('transModalCtrl', transModalCtrl)
    .controller('transBondInfoCtrl', transBondInfoCtrl)
    .controller('transChangeCtrl', transChangeCtrl)
    .controller('transChangeModalCtrl', transChangeModalCtrl)
    .controller('transRefundCtrl', transRefundCtrl)
    .controller('transRefusedCtrl', transRefusedCtrl)
    .controller('balanceInquiryCtrl', balanceInquiryCtrl)
    .controller('balanceInquiryModalCtrl', balanceInquiryModalCtrl)
    .controller('withdrawDepositInquiryCtrl', withdrawDepositInquiryCtrl)
    .controller('baseInformationCtrl', baseInformationCtrl)
    .controller('configurationInformation', configurationInformation)
    .controller('paymentInformation', paymentInformation)
    .controller('userMgmtCtrl', userMgmtCtrl)
    .controller('userMgmtModalCtrl', userMgmtModalCtrl)
    .controller('roleMgmtCtrl', roleMgmtCtrl)
    .controller('roleMgmtModalCtrl', roleMgmtModalCtrl)
    .controller('secretKeyChangeCtrl', secretKeyChangeCtrl)
    .controller('opinionCtrl', opinionCtrl)
    .controller('opinionModalCtrl', opinionModalCtrl)
    .controller('webSiteMgmtCtrl', webSiteMgmtCtrl)
    .controller('webSiteMgmtModalCtrl', webSiteMgmtModalCtrl)
    .controller('logisticsMgmtCtrl', logisticsMgmtCtrl)
    .controller('logisticsMgmtModalCtrl', logisticsMgmtModalCtrl)
    .controller('logisticsMgmtUploadModalCtrl', logisticsMgmtUploadModalCtrl);

function verification(value, htmlId) {
    if (value === undefined || value === null || value === '') {
        angular.element(htmlId).parent().removeClass('has-success');
        angular.element(htmlId).parent().addClass('has-error');
        return true;
    } else {
        angular.element(htmlId).parent().removeClass('has-error');
        angular.element(htmlId).parent().addClass('has-success');
        return false;
    }
}

function inputRegex(input, regex, replacement) {
    if (replacement === undefined || replacement === null)
        replacement = '';
    input.value = input.value.replace(regex, replacement);
}